package com.boolib.service.impl;

import com.boolib.commons.Const;
import com.boolib.commons.entity.ServerResponse;
import com.boolib.load.mail.IMailService;
import com.boolib.commons.util.PasswordUtil;
import com.boolib.dao.ShopUserMapper;
import com.boolib.dao.SysUserMapper;
import com.boolib.pojo.ShopUser;
import com.boolib.pojo.ShopUserExample;
import com.boolib.pojo.SysUser;
import com.boolib.pojo.SysUserExample;
import com.boolib.service.IAdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SysUserServiceImpl  implements IAdminService {



    @Value("${mail.from}")
    private String fromMail ;


    @Value("${mail.title}")
    private String  mailTitle;


    @Autowired
    private IMailService mailService;


    @Autowired
    private ShopUserMapper shopUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;





    @Override
    public ServerResponse<SysUser> sysUserLoginAuth(SysUser sysUser) {

        if(Strings.isBlank(sysUser.getUsername())||Strings.isBlank(sysUser.getPassword())){
            return  ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),
                    Const.System.Status.ARGUMENTNULL.getMessage()
                    );
        }



        SysUser temp = new SysUser();

        temp.setUsername(sysUser.getUsername());




        SysUser resultUser = sysUserMapper.selectOne(temp);


        if(resultUser == null){
            return  ServerResponse.createByError(Const.User.Status.USERNOTEXIST.getCode(),Const.User.Status.USERNOTEXIST.getMessage());
        }

        ServerResponse serverResponse = checkUserState(resultUser);

        if(!serverResponse.isSuccess()) return  serverResponse;



        String salt = resultUser.getSalt();


        String encryptPass = PasswordUtil.getEncryptPass5(sysUser.getPassword(),salt);


        if(encryptPass.equals(resultUser.getPassword())){
            resultUser.setDelFlag(null);
            resultUser.setPassword(null);
            resultUser.setSalt(null);
            return ServerResponse.createBySuccess(resultUser);
        }

        return ServerResponse.createByError(Const.User.Status.PASSWORDFAILD.getCode(),Const.User.Status.PASSWORDFAILD.getMessage());

    }

    @Override
    public ServerResponse sysUserRegister(SysUser sysUser) {


        if(Strings.isBlank(sysUser.getUsername())|| Strings.isBlank(sysUser.getPassword())||Strings.isBlank(sysUser.getEmail())
                ||Strings.isBlank(sysUser.getPhonenumber())||sysUser.getRole() == null){
            return ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),
                    Const.System.Status.ARGUMENTNULL.getMessage());
        }


        if(sysUser.getRole().equals(Const.SysUser.ADMINISTRATOR)){
            return ServerResponse.createByError(Const.System.Status.PERMISSIONDENIED.getCode()
                    ,Const.System.Status.PERMISSIONDENIED.getMessage());
        }

        ServerResponse   serverResponse = checkUsername(sysUser.getUsername()) ;

        if(!serverResponse.isSuccess()) return serverResponse;

        serverResponse = checkPhoneNumber(sysUser.getPhonenumber()) ;

        if(!serverResponse.isSuccess()) return serverResponse;

        serverResponse = checkEmail(sysUser.getEmail());

        if(!serverResponse.isSuccess()) return serverResponse;




        String salt  =  PasswordUtil.getSalt();


        sysUser.setSalt(salt);


        sysUser.setPassword(PasswordUtil.getEncryptPass5(sysUser.getPassword(),salt));

        sysUser.setCreateTime(new Date());


        sysUser.setUpdateTime(new Date());



        if(sysUserMapper.insertSelective(sysUser)>0){
            return  ServerResponse.createBySuccessMessage("系统用户注册成功");
        }



        return ServerResponse.createBySuccessMessage("系统用户注册失败");
    }


    @Override
    public ServerResponse sysUserForgetPassword(String username) {


        if(Strings.isBlank(username)) return  ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),Const.System.Status.ARGUMENTNULL.getMessage());


        SysUser  temp = new SysUser();

        temp.setUsername(username);

        SysUser resultUser = sysUserMapper.selectOne(temp);

        ServerResponse serverResponse = checkUserState(resultUser);


        if(!serverResponse.isSuccess()){
            return  serverResponse;
        }

        String email = resultUser.getEmail();

        if(Strings.isBlank(email)){
            return ServerResponse.createByError(Const.User.Status.UNBINDMAIL.getCode(),Const.User.Status.UNBINDMAIL.getMessage());
        }


        mailService.sendSysUserForgetMail(fromMail,email,mailTitle,resultUser.getId());

        Map map = Maps.newHashMap();

        map.put("sysUserId",resultUser.getId());

        return ServerResponse.createBySuccess("已经发送需要跳转到指定页面",map);
    }


    @Override
    public ServerResponse sysUserAlterPasswordBeforeLogin(Integer id, String password, String code) {





        if(id == null || Strings.isBlank(password) ||Strings.isBlank(code)){
            log.error("参数为空");
            return    ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),Const.System.Status.ARGUMENTNULL.getMessage());
        }

        ServerResponse serverResponse = mailService.checkSysUserMailToken(id,code);

        if(!serverResponse.isSuccess()) return serverResponse;

        serverResponse    = checkExist(id);

        if(!serverResponse.isSuccess()) return serverResponse;

        SysUser temp = (SysUser) serverResponse.getData();

        String salt =   temp.getSalt();

        String encryptPass = PasswordUtil.getEncryptPass5(password,salt);


        SysUser update =  new SysUser();

        update.setId(id);

        update.setPassword(encryptPass);

        update.setUpdateTime(new Date());

        if(sysUserMapper.updateByPrimaryKeySelective(update)>0)
            return ServerResponse.createBySuccessMessage("更新成功");
        return ServerResponse.createByErrorMessage("更新失败");


    }


    @Override
    public ServerResponse sysUserAlterPasswordAfterLogin(Integer id, String password) {


        if(id == null || Strings.isBlank(password)) return ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),
                Const.System.Status.ARGUMENTNULL.getMessage());

        SysUser temp = new SysUser();

        temp.setId(id);

        SysUser result=  sysUserMapper.selectOne(temp);

        ServerResponse serverResponse =   checkUserState(result);

        if(!serverResponse.isSuccess()) return  serverResponse;


        password = PasswordUtil.getEncryptPass5(password, result.getSalt());

        SysUser t = new SysUser();


        t.setId(id);

        t.setUpdateTime(new Date());

        t.setPassword(password);

        if(sysUserMapper.updateByPrimaryKeySelective(t)>0){
            return  ServerResponse.createBySuccessMessage("密码更新成功");
        }

        return ServerResponse.createByErrorMessage("密码更新失败");
    }



    @Override
    public ServerResponse sysUserSelectShopUserNormal(int pageNum, int pageSize) {

        ShopUser shopUser = new ShopUser();

        shopUser.setDelFlag(0);

        shopUser.setStatus(0);

        List<ShopUser> shopUsers =  shopUserMapper.select(shopUser);

        PageHelper.startPage(pageNum,pageSize);


        PageInfo pageInfo = new PageInfo();

        pageInfo.setList(shopUsers);


        return ServerResponse.createBySuccess(pageInfo);


    }

    @Override
    public ServerResponse sysUserSelectShopUserAbnormal(int pageNum, int pageSize) {

        ShopUserExample shopUserExample = new ShopUserExample();

        ShopUserExample.Criteria criteria =    shopUserExample.createCriteria();

        criteria.andStatusGreaterThanOrEqualTo(1);
        shopUserExample.or().andDelFlagGreaterThanOrEqualTo(1);



        List<ShopUser> lists =  shopUserMapper.selectByExample(shopUserExample);



        PageHelper.startPage(pageNum,pageSize);

        PageInfo pageInfo = new PageInfo();

        pageInfo.setList(lists);


        return ServerResponse.createBySuccess(pageInfo);

    }

    @Override
    public ServerResponse sysUserSelectSysUserNormal(int pageNum, int pageSize) {



        SysUserExample sysUserExample = new SysUserExample();

        SysUserExample.Criteria criteria  = sysUserExample.createCriteria();

        criteria.andDelFlagEqualTo(0).andStatusEqualTo(0);

        List<SysUser> lists=   sysUserMapper.selectByExample(sysUserExample);

        PageHelper.startPage(pageNum,pageSize);

        PageInfo pageInfo = new PageInfo();

        pageInfo.setList(lists);

        return ServerResponse.createBySuccess(pageInfo);

    }



    @Override
    public ServerResponse sysUserSelectSysUserAbnormal(int pageNum, int pageSize) {
        SysUserExample sysUserExample = new SysUserExample();

        SysUserExample.Criteria criteria  = sysUserExample.createCriteria();

        criteria.andDelFlagGreaterThan(0);

        sysUserExample.or().andStatusGreaterThan(0);

        List<SysUser> lists=   sysUserMapper.selectByExample(sysUserExample);

        PageHelper.startPage(pageNum,pageSize);

        PageInfo pageInfo = new PageInfo();

        pageInfo.setList(lists);

        return ServerResponse.createBySuccess(pageInfo);
    }


    private ServerResponse checkExist(Integer id){

        SysUser sysUser  = new SysUser();
        sysUser.setId(id);

        SysUser temp = sysUserMapper.selectOne(sysUser);

        if(temp==null){
            return ServerResponse.createByError(Const.User.Status.EMAILEXIST.getCode(),Const.User.Status.EMAILEXIST.getMessage());
        }

        return  ServerResponse.createBySuccess(temp);

    }

    private ServerResponse checkEmail(String email){

        SysUser sysUser  = new SysUser();
        sysUser.setEmail(email);

        List lists = sysUserMapper.select(sysUser);

        if(lists.size()>0){
            return ServerResponse.createByError(Const.User.Status.EMAILEXIST.getCode(),Const.User.Status.EMAILEXIST.getMessage());
        }

        return  ServerResponse.createBySuccess();

    }

    private ServerResponse checkUsername(String username){

        SysUser sysUser  = new SysUser();
        sysUser.setUsername(username);

        List lists = sysUserMapper.select(sysUser);

        if(lists.size()>0){
            return ServerResponse.createByError(Const.User.Status.USEREXIST.getCode(),Const.User.Status.USEREXIST.getMessage());
        }

        return  ServerResponse.createBySuccess();
    }

    private ServerResponse checkPhoneNumber(String phoneNumber){

        SysUser sysUser  = new SysUser();

        sysUser.setPhonenumber(phoneNumber);

        List lists = sysUserMapper.select(sysUser);

        if(lists.size()>0){
            return ServerResponse.createByError(Const.User.Status.PHONEEXIST.getCode(),Const.User.Status.PHONEEXIST.getMessage());
        }

        return  ServerResponse.createBySuccess();
    }


    private ServerResponse checkUserState(SysUser resultUser){
        if(resultUser == null )
            return ServerResponse.createByError(
                    Const.User.Status.USERNOTEXIST.getCode(),
                    Const.User.Status.USERNOTEXIST.getMessage()
            );

        if(resultUser.getDelFlag()>0){
            return ServerResponse.createByError(Const.User.Status.LOGINFAILD.getCode()
                    ,Const.User.Status.LOGINFAILD.getMessage());
        }

        if(resultUser.getStatus()>0){

            return  ServerResponse.createByError(Const.User.Status.USERFORBID.getCode(), "用户状态异常");
        }


        return  ServerResponse.createBySuccess();

    }


}
